<template>
  <fullscreen :fullscreen.sync="fullscreen" class="container">
    <div class="header">
      <div class="time">
        <span>{{ timeObj.year }}{{ timeObj.date }}</span
        ><span>{{ timeObj.week }}</span
        ><span>{{ timeObj.time }}</span>
      </div>
      <div @click="toggle" class="btn">
        <img src="@/assets/images/exhibition/fullbtn.png" alt="" />{{
          fullscreen ? '退出全屏' : '全屏展示'
        }}
      </div>
    </div>
    <div class="content">
      <div class="left">
        <leftTrendPane
          :data="trendData"
          :today-data="todayData"
        ></leftTrendPane>
      </div>
      <div class="middle">
        <div class="area">
          <img src="@/assets/images/exhibition/locationicon.png" alt="" />
          <span>{{ areaName }}</span>
        </div>
        <div class="top-data">
          <div
            class="num-item"
            v-for="(item, key, index) in topPanelData"
            :key="index"
          >
            <span>{{ item.label }}</span>
            <span>{{ item.value }}</span>
            <span>{{ item.unit }}</span>
          </div>
        </div>
        <div class="map">
          <div id="preview-map" class="preview-map-container">
            地图加载中...
          </div>
        </div>
        <ChargingBehavior :data="behaviorData"></ChargingBehavior>
      </div>
      <div class="right">
        <ChargingRanking
          :data="portRankingData"
          title="端口数排名Top5"
          id="port-ranking"
        ></ChargingRanking>
        <ChargingRanking
          :data="chargingRankingData"
          title="近七日充电次数排名Top5"
          id="charge-ranking"
        ></ChargingRanking>
        <ConserveEnergy
          :today-data="todayData"
          :total-data="totalData"
        ></ConserveEnergy>
        <ChargingProtect
          :data="alarmListData"
          :today-data="todayData"
          :total-data="totalData"
        ></ChargingProtect>
      </div>
    </div>
  </fullscreen>
</template>
<script>
import fullscreen from 'vue-fullscreen'
import Vue from 'vue'
Vue.use(fullscreen)
import _ from 'lodash'
import { debounce } from '@/utils'
import {
  dataToday,
  trendStatistics,
  topData,
  mapData,
  pieChart,
  areaDevice,
  areaBill,
  alarmList,
} from '@/api/dashboard'
// import { loadMap } from '@/utils/map-loaderV3'
// import mapSettings from './config/mapSetting2'
import AMapLoader from '@amap/amap-jsapi-loader'
// import getCustomOverlay from '@/utils/CustomOverlay'
import leftTrendPane from './components/leftTrendPane.vue'
import ChargingBehavior from './components/ChargingBehavior.vue'
import ChargingRanking from './components/ChargingRanking.vue'
import ConserveEnergy from './components/ConserveEnergy.vue'
import ChargingProtect from './components/ChargingProtect.vue'

const zoomRange = ['country', 'province', 'city', 'district']
const zoomLevel = {
  country: {
    min: 3,
    max: 6,
  },
  province: {
    min: 6,
    max: 10,
  },
  city: {
    min: 10,
    max: 11,
  },
  district: {
    min: 11,
    max: 13,
  },
}
const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
let clickRecord = {}

export default {
  name: 'Statistics',
  components: {
    leftTrendPane,
    ChargingBehavior,
    ChargingRanking,
    ConserveEnergy,
    ChargingProtect,
  },
  data() {
    return {
      aMapZoomChangeLister: null,
      lastZoom: null,
      initCenterPoint: [116.397085, 39.908703],
      fullscreen: false,
      map: null,
      zoom: 'country',
      zoomId: null,
      mapQueryParams: {
        zoom: 'country',
        zoomId: null,
      },
      overlayData: [],
      overlayList: [],
      maskoverlay: null,
      isControl: false,
      isClick: false,
      isResize: false,
      timerList: [],
      areaName: '全国',
      timeObj: {},
      trendData: {},
      todayData: {},
      totalData: {},
      behaviorData: {},
      alarmListData: [],
      portRankingData: [],
      chargingRankingData: [],
      topPanelData: {
        stationAmount: {
          label: '电站数',
          value: 0,
          unit: '个',
        },
        portAmount: {
          label: '端口数',
          value: 0,
          unit: '个',
        },
        userAmount: {
          label: '用户数',
          value: 0,
          unit: '个',
        },
        totalBill: {
          label: '充电次数',
          value: 0,
          unit: '次',
        },
      },
    }
  },
  watch: {
    overlayList(val) {
      val.forEach((item) => this.map.add(item))
    },
    deep: true,
  },
  methods: {
    toggle() {
      this.fullscreen = !this.fullscreen
      this.initCenterPoint = this.map.getCenter()
    },
    _getLastTime() {
      this.timeObj = {
        year: new Date().getFullYear() + '年',
        date: new Date().getMonth() + 1 + '月' + new Date().getDate() + '日',
        time: new Date()
          .toLocaleString('chinese', { hour12: false })
          .split(' ')[1],
        week: weekday[new Date().getDay()],
      }
    },
    _initPanelData() {
      this._getTrendData()
      this._getTodayData()
      this._getTopData()
      this._getAreaDeviceData()
      this._getAreaBilleData()
      this._getBehaviorData()
      this._getAlarmList()
    },
    _getTodayData() {
      dataToday({ zoom: this.zoom, zoomId: this.zoomId }).then((res) => {
        this.todayData = res
      })
    },
    _getTrendData() {
      trendStatistics({ zoom: this.zoom, zoomId: this.zoomId }).then((res) => {
        this.trendData = res
      })
    },
    _getAlarmList() {
      alarmList({ zoom: this.zoom, zoomId: this.zoomId }).then((res) => {
        this.alarmListData = res
      })
    },
    _getTopData() {
      topData({ zoom: this.zoom, zoomId: this.zoomId }).then((res) => {
        Object.keys(res).forEach((key) => {
          if (this.topPanelData[key]) {
            this.topPanelData[key].value = res[key]
          }
        })
        this.totalData = res
      })
    },
    _getAreaDeviceData() {
      areaDevice({ zoom: this.zoom, zoomId: this.zoomId }).then((res) => {
        let data = []
        res.forEach((item) => {
          data.push({
            name: item.areaName,
            val: item.deviceNum,
          })
        })
        this.portRankingData = data
      })
    },
    _getAreaBilleData() {
      areaBill({ zoom: this.zoom, zoomId: this.zoomId }).then((res) => {
        let data = []
        res.forEach((item) => {
          data.push({
            name: item.areaName,
            val: item.billNum,
          })
        })
        this.chargingRankingData = data
      })
    },
    _getBehaviorData() {
      pieChart({ zoom: this.zoom, zoomId: this.zoomId }).then((res) => {
        this.behaviorData = res
      })
    },
    _registMapEvents() {
      if (!this.map) return
      window.onresize = () => {
        this.map.setCenter(this.initCenterPoint)
        this.isResize = true
      }

      window.AMap.event.addListener(this.map, 'complete', () => {
        this.isControl = true
      })

      this.aMapZoomChangeLister = window.AMap.event.addListener(
        this.map,
        'zoomchange',
        debounce(async () => {
          if (!this.isControl) return
          if (this.isClick) {
            this.isClick = false
            return
          }

          if (!this.lastZoom) {
            this.lastZoom = this.map.getZoom()
          }
          var currentZoom = this.map.getZoom()

          if (this.lastZoom < currentZoom) {
            this.lastZoom = currentZoom
          } else {
            this.mapQueryParams = this._getMapParams()
            this.mapQueryParams.zoom === 'country'
              ? this._initParams({
                  zoomId: null,
                  zoom: 'country',
                  areaName: '全国',
                  initCenterPoint: this.initCenterPoint,
                })
              : this._getMapData()
          }
        })
      )
    },
    _getMapData() {
      mapData(this.mapQueryParams).then((res) => {
        if (_.isEqual(this.overlayData, res)) return
        this.overlayData = res
        this._createOverlay2()
      })
    },
    _createOverlay2() {
      if (!this.map) return
      this.overlayList.forEach((item) => this.map.remove(item))
      this.overlayList = []
      this.overlayData.forEach((item) => {
        let index = zoomRange.findIndex(
          (item) => item === this.mapQueryParams.zoom
        )
        let indexNext = index === zoomRange.length - 1 ? index : index + 1
        let zoomNext = zoomRange[indexNext]
        let address = zoomRange
          .slice(1, indexNext + 1)
          .map((key) => item[key])
          .join('')
        if (index === zoomRange.length - 1) {
          var text = new window.AMap.Text({
            text: `${item.stationName}，端口数:${item.plugNum}`,
            position: new window.AMap.LngLat(item.stationLng, item.stationLat),
            style: {
              position: 'absolute',
              padding: '6px 10px',
              'border-radius': '10px',
              'background-color': '#649c00',
              color: '#fff',
              'font-size': '12px',
              'text-align': 'center',
              'background-clip': 'padding-box',
              'z-index': '1000',
            },
          })
          this.overlayList.push(text)
        } else {
          var PlaceSearchOptions = {
            city: '全国',
            pageSize: 10,
            pageIndex: 1,
            extensions: 'base',
          }

          var MapSearch = new window.AMap.PlaceSearch(PlaceSearchOptions) //构造PlaceSearch类
          window.AMap.event.addListener(MapSearch, 'complete', (results) => {
            let point = results.poiList.pois[0].location
            var markerContent = `<div class="pointOverlay2" title="${item[zoomNext]}（电站数：${item.stationNum}, 插口数：${item.plugNum})"><div class="pointOverlayTop">${item[zoomNext]}</div><div>${item.stationNum}</div><div>${item.plugNum}</div></div>`
            var marker = new window.AMap.Marker({
              position: new window.AMap.LngLat(point.lng, point.lat),
              content: markerContent,
              offset: new window.AMap.Pixel(-40, -40),
            })
            marker.on('click', () => {
              this.isClick = true
              if (this.map.getZoom() < zoomLevel[zoomNext].min + 1) {
                this.map.setZoomAndCenter(zoomLevel[zoomNext].min + 1, point)
              }

              clickRecord[this.mapQueryParams.zoom] = {
                zoom: this.mapQueryParams.zoom,
                zoomId: this.mapQueryParams.zoomId,
              }

              this.mapQueryParams = {
                zoom: zoomNext,
                zoomId: item.areaCode,
              }

              this._initParams({
                zoom: zoomNext,
                zoomId: item.areaId,
                areaName: address,
                initCenterPoint: [point.lng, point.lat],
              })
            })
            marker.on('mouseover', () => {
              marker.setzIndex(99999)
            })
            marker.on('mouseout', () => {
              marker.setzIndex(1)
            })
            this.overlayList.push(marker)
          })

          MapSearch.search(address) //关键字查询
        }
      })
    },
    initMap() {
      AMapLoader.load({
        key: process.env.VUE_APP_AMAP_AK, // 申请好的Web端开发者Key，首次调用 load 时必填
        // version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.PlaceSearch', 'AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map('preview-map', {
            zoom: 5, //初始化地图级别
            center: this.initCenterPoint, //初始化地图中心点位置
            zooms: [5, 20],
            doubleClickZoom: false,
            scrollWheel: true,
            mapStyle: process.env.VUE_APP_AMAP_STYLE,
          })
          this._registMapEvents()
          this._getMapData()
        })
        .catch((e) => {
          console.log(e)
        })
    },
    _initParams({ zoomId, zoom, areaName, initCenterPoint }) {
      this.zoomId = zoomId
      this.zoom = zoom
      this.areaName = areaName
      this.initCenterPoint = initCenterPoint
      this._initPanelData()
      this._getMapData()
    },
    _getZoomLevel() {
      if (!this.map) return
      let zoom
      let zoomNum = this.map.getZoom()
      zoom =
        (zoomNum <= zoomLevel.country.max && 'country') ||
        (zoomNum <= zoomLevel.province.max && 'province') ||
        (zoomNum <= zoomLevel.city.max && 'city') ||
        (zoomNum > zoomLevel.district.min && 'district')
      return zoom
    },
    _getMapParams() {
      let zoom = this._getZoomLevel()
      return {
        zoom: zoom,
        zoomId: zoom === 'country' ? null : clickRecord[zoom].zoomId,
      }
    },
  },
  created() {
    this._getLastTime()
    this._initPanelData()
  },
  activated() {
    // let timerPanel = setInterval(this._initPanelData, 10000)
    // let timerMap = setInterval(this._getMapData, 10000)
    let timerTime = setInterval(this._getLastTime, 1000)
    // this.timerList = [timerPanel, timerMap, timerTime]
    this.timerList = [timerTime]
    if (this.map) {
      this._registMapEvents()
    }
  },
  deactivated() {
    window.onresize = null
    this.timerList.forEach((item) => clearInterval(item))
    this.timerList = []
    if (this.map) {
      if (this.aMapZoomChangeLister) {
        window.AMap.event.removeListener(this.aMapZoomChangeLister)
      }
    }
  },
  deystroyed() {
    window.onresize = null
    this.timerList.forEach((item) => clearInterval(item))
    this.timerList = []
    if (this.map) {
      if (this.aMapZoomChangeLister) {
        window.AMap.event.removeListener(this.aMapZoomChangeLister)
      }
    }
  },
  mounted() {
    this.initMap()
  },
}
</script>
<style lang="scss" scoped>
.container {
  height: 100%;
  width: 100%;
  position: relative;
  background: url(../../assets/images/exhibition/bgimg.png) center center
    no-repeat;
  background-size: 100% 100%;
  .header {
    height: 124px;
    width: 100%;
    background: url(../../assets/images/exhibition/headerbg.png) center center
      no-repeat;
    background-size: cover;
    .time {
      position: absolute;
      top: 40px;
      left: 30px;
      font-size: 16px;
      color: #ffffff;
      span:nth-child(2) {
        margin: auto 10px;
      }
    }
    .btn {
      position: absolute;
      top: 32px;
      right: 30px;
      z-index: 9999;
      cursor: pointer;
      width: 112px;
      height: 40px;
      border: 1px solid #ffffff;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ffffff;
      font-size: 14px;
      img {
        width: 20px;
        height: 20px;
        margin-right: 4px;
      }
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 124px);
    display: flex;
    justify-content: space-between;
    & > div {
      height: 100%;
    }
    .left {
      width: 25%;
      height: 100%;
      padding-left: 27px;
      box-sizing: border-box;
    }
    .middle {
      width: 50%;
      height: 100%;
      .area {
        margin-top: 28px;
        text-align: center;
        img {
          vertical-align: middle;
        }
        span {
          font-size: 16px;
          font-weight: bold;
          color: #ffffff;
          margin-left: 10px;
          vertical-align: middle;
        }
      }
      .top-data {
        display: flex;
        justify-content: space-around;
        margin-top: 28px;
        .num-item {
          width: 24%;
          height: 54px;
          background: url(../../assets/images/exhibition/numbg.png) center
            center no-repeat;
          background-size: 100% 100%;
          text-align: center;
          display: flex;
          justify-content: space-around;
          align-items: center;
          span:nth-child(1) {
            font-size: 14px;
            color: #ffffff;
          }
          span:nth-child(2) {
            font-size: 24px;
            font-weight: bold;
            color: #6de3fd;
          }
          span:nth-child(3) {
            width: 13px;
            height: 16px;
            font-size: 12px;
            color: #ffffff;
            opacity: 0.69;
          }
        }
      }
      .map {
        width: 100%;
        height: calc(70% - 146px);
        background: url(../../assets/images/exhibition/mapbg.png) center center
          no-repeat;
        background-size: 100% 100%;
        margin-top: 10px;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
        .preview-map-container {
          width: calc(100% - 10px);
          height: calc(100% - 10px);
          margin: auto;
          background: #0c0d0f !important;
        }
      }
    }
    .right {
      width: 25%;
      height: 100%;
    }
  }
  ::v-deep .title {
    width: 90%;
    font-size: 16px;
    font-weight: bold;
    color: #ffffff;
    margin-top: 7px;
    margin-bottom: 7px;
  }
}
@media screen and (max-width: 1440px) {
  .container {
    .header {
      height: 100px;
      .time {
        font-size: 14px;
        top: 34px;
        left: 10px;
      }
      .btn {
        height: 30px;
        top: 28px;
        right: 10px;
        font-size: 12px;
      }
    }
    .content {
      height: calc(100% - 100px);
      .left {
        padding-left: 4px;
      }
      .middle {
        .area {
          margin-top: 14px;
          span {
            font-size: 14px;
          }
        }
        .top-data {
          margin-top: 14px;
          .num-item {
            span:nth-child(1) {
              font-size: 12px;
            }
            span:nth-child(2) {
              font-size: 16px;
            }
            span:nth-child(3) {
              font-size: 12px;
            }
          }
        }
        .map {
          height: calc(70% - 110px);
          margin-top: 5px;
        }
      }
    }
    ::v-deep .title {
      width: 100%;
      font-size: 12px;
      margin-top: 5px;
      margin-bottom: 5px;
    }
  }
}
</style>
